﻿<!DOCTYPE html>
<html>
<head>
	<title>A JsViews tree view control</title>
	<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
	<script src="../../jsrender.js" type="text/javascript"></script>
	<script src="../../jquery.observable.js" type="text/javascript"></script>
	<script src="../../jquery.views.js" type="text/javascript"></script>
	<link href="../resources/demos.css" rel="stylesheet" type="text/css" />
	<link href="../resources/tree.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="nav"><a href="../demos.html">JsViews Demos</a></div>

<h3>JsViews 'Editable Tree' Tag Control: The {{tree}} tag</h3>
<div class="subhead">Dynamic content blocks use <em>{^{if}}</em> binding</div>

<div id="pageContent" class="folderView"></div>

<script id="pageTemplate" type="text/x-jsrender">
	<ul>{^{tree/}}</ul>
</script>

<script id="treeTemplate" type="text/x-jsrender">
	<li>
		{^{if folders.length}}
			<span class="toggle">{^{:expanded ? '-' : '+'}}</span>
		{{else}}
			<span class="spacer">></span>
		{{/if}}
		<input data-link="name" />
		<span class="add">add</span>
		{^{if ~parentTags.tree}}
			{{!-- Don't allow removing the top-level tree control --}}
			<img class="remove" src="../resources/close.png" />
		{{/if}}
	</li>
	{^{if expanded}}
		<li>
			<ul>
				{^{for folders}}
					{^{tree/}}
				{{/for}}
			</ul>
		</li>
	{{/if}}
</script>

<script type="text/javascript">

$.views.tags({
	tree: {
		init: function(tagCtx, linkCtx, ctx) {
			this.data = tagCtx.view.data;
		},
		toggle: function() {
			$.observable(this.data).setProperty("expanded", !this.data.expanded);
		},
		remove: function() {
			var parentFolders = this.parent.data.folders,
				index = this.tagCtx.view.index;
			$.observable(parentFolders).remove(index);
		},
		addFolder: function() {
			$.observable(this.data.folders).insert(this.data.folders.length, {
				name: "new folder",
				folders: []
			});
			$.observable(this.data).setProperty("expanded", true);
		},
		template: "#treeTemplate"
	}
});

/* Hierarchy of named folders */
var rootFolder = {
	name: "Categories", folders: [
		{ name: "Drama", folders: [
			{ name: "Courtroom", folders: [] },
			{ name: "Political", folders: [] }
		]},
		{ name: "Classic", folders: [
			{ name: "Musicals", folders: [
				{ name: "Jazz", folders: [] },
				{ name: "R&B/Soul", folders: [] }
			]}
		]}
	]};

var pageTmpl = $.templates("#pageTemplate");

$( "#pageContent")
	.on( "click", ".toggle", function() {
		$.view(this).ctx.tag.toggle();
	})
	.on( "click", ".remove", function() {
		$.view(this).ctx.tag.remove();
	})
	.on( "click", ".add", function() {
		$.view(this).ctx.tag.addFolder();
	});

$( "#pageContent").link(pageTmpl, rootFolder);

</script>
</body>
</html>
